from GrpLabels_Mngr import GrpLabels_Mngr;
from TrackPath_Item import TrackPath_Item;
from PyQt4 import QtGui, QtCore;
import numpy as np;

class MovieScene_Canvas(QtGui.QGraphicsView):
    def __init__(self, dataModel, gSceneView):
        QtGui.QGraphicsView.__init__(self);        
        self.gPixmapItem = None;
        self.dTrackPaths = {};
        self.dataModel = dataModel;
        self.gSceneView = gSceneView;

    def createScene(self):
        self.graphicsScene = QtGui.QGraphicsScene(self);
        self.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff);
        self.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff); 
        self.setRenderHint(QtGui.QPainter.Antialiasing, True);
        self.setRenderHint(QtGui.QPainter.HighQualityAntialiasing, True);        
        self.setScene(self.graphicsScene); #Set Scene
        self.grpLbls = GrpLabels_Mngr(self);
        
    def loadFrames(self, aNames):
        if self.gPixmapItem is not None:
            self.graphicsScene.removeItem(self.gPixmapItem);
        self.sPath, self.sFileName, self.nZeros, self.sFileExt = aNames;
        qImg = QtGui.QPixmap(self.sPath+"/"+self.sFileName+str(0).zfill(self.nZeros)+"."+self.sFileExt);
        self.gPixmapItem = QtGui.QGraphicsPixmapItem(qImg);
        self.graphicsScene.addItem(self.gPixmapItem);
        self.gPixmapItem.setZValue(-1);
        self.ensureVisible(self.gPixmapItem.boundingRect());
        
    def setFrame(self, nFrm):
        self.updatePathTracks(nFrm);
        if self.gPixmapItem==None: return;
        qImg = QtGui.QPixmap(self.sPath+"/"+self.sFileName+str(nFrm).zfill(self.nZeros)+"."+self.sFileExt);
        self.gPixmapItem.setPixmap(qImg);
        
    def create_Track_Items(self, dfTracks):
        #Clear all Old Track Items first
        for trk in self.dTrackPaths.values():
            trk.removeTrack(self.graphicsScene);
        self.dTrackPaths.clear();
        self.grpLbls.clear_GrpLabels();
        #Create the Track Items
        for iTrk, dfTrk in dfTracks.groupby("TrackId"):
            aFrms = np.array(dfTrk.values[:, 1], dtype=np.int); #Get Column Frm
            aPos = dfTrk.values[:, 2:4]; #Get Columns PosX, PosY
            trk_Item = TrackPath_Item(iTrk, aFrms, aPos*0.5, self.graphicsScene); #aPos*10+100
            self.dTrackPaths[iTrk] = trk_Item;
        if self.dataModel.dfGrpActs is None:
            print "Grp Acts Graph Table must be loaded in order to show Track Groups.";
            return;
        self.grpLbls.create_GrpLabelsTbl(self.dataModel.dfGrpActs);
        
    def updatePathTracks(self, nFrm, nWin=100):
        for trackPath in self.dTrackPaths.values():
            trackPath.updateTrackPath(nFrm, nWin);
        self.grpLbls.updateGrpLabels(nFrm);
        
    def showGrpActs(self, bShow):
        self.grpLbls.setVisible(bShow);
        

